// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @file zeroCopySubscriber.cpp
 *
 */
#include <fastrtps/Domain.h>
#include <fastdds/dds/domain/DomainParticipantFactory.hpp>
#include <fastdds/dds/publisher/qos/DataWriterQos.hpp>
#include <fastdds/dds/subscriber/qos/DataReaderQos.hpp>
#include <fastdds/dds/subscriber/SampleInfo.hpp>
#include <fastdds/rtps/common/Locator.h>
#include <fastdds/rtps/transport/TCPv4TransportDescriptor.h>
#include <fastdds/rtps/transport/TCPv6TransportDescriptor.h>
#include "zeroCopySubscriber.hpp"


using namespace std;
using namespace eprosima::fastdds::dds;
using namespace eprosima::fastdds::rtps;
using IPLocator = eprosima::fastrtps::rtps::IPLocator;

zeroCopySubscriber::zeroCopySubscriber()
    : mp_participant(nullptr)
    , mp_subscriber(nullptr)
    , mp_reader(nullptr)
    , mp_topic_sub(nullptr)
    , m_subListener(this)
    , m_type(new messDataPubSubType())
    , m_typeSmall(new smallDataPubSubType())
    , m_typeMedium(new mediumDataPubSubType())
    , m_typeBig(new bigDataPubSubType())
{
#ifdef VEC_DEBUG
    // m_vSimplesTime0.resize(5000);
    // m_vSimplesTime1.resize(5000);
#else
    memset(m_iSimplesTime,0,sizeof(m_iSimplesTime));
#endif
}

bool zeroCopySubscriber::init(
        int transport,
        ReliabilityQosPolicyKind reliabilityKind,
        const std::string& topicName,
        int domain,
        int loan, 
        int size)
{
    m_iSize = size;
    m_iLoan = loan;
    //CREATE THE PARTICIPANT
    DomainParticipantQos pqos;
    // pqos.wire_protocol().builtin.discovery_config.leaseDuration = eprosima::fastrtps::c_TimeInfinite;
    // pqos.wire_protocol().builtin.discovery_config.leaseDuration_announcementperiod = Duration_t(1, 0);
    pqos.name("Participant_sub");

    if (transport == 1)
    {
        pqos.transport().use_builtin_transports = true;
    }
    else if (transport == 2)
    {
        int32_t kind = LOCATOR_KIND_TCPv4;

        Locator initial_peer_locator;
        initial_peer_locator.kind = kind;
        IPLocator::setIPv4(initial_peer_locator, "127.0.0.1");
        initial_peer_locator.port = 5100;
        pqos.wire_protocol().builtin.initialPeersList.push_back(initial_peer_locator); // Publisher's channel

        pqos.transport().use_builtin_transports = false;
        std::shared_ptr<TCPv4TransportDescriptor> descriptor = std::make_shared<TCPv4TransportDescriptor>();
        descriptor->sendBufferSize = 8912896; // 8.5Mb
        descriptor->receiveBufferSize = 8912896; // 8.5Mb
        pqos.transport().user_transports.push_back(descriptor);
    }
    else if (transport == 3)
    {
        //uint32_t kind = LOCATOR_KIND_UDPv6;
    }
    else if (transport == 4)
    {
        uint32_t kind = LOCATOR_KIND_TCPv6;
        pqos.transport().use_builtin_transports = false;

        Locator initial_peer_locator;
        initial_peer_locator.kind = kind;
        IPLocator::setIPv6(initial_peer_locator, "::1");
        initial_peer_locator.port = 5100;
        pqos.wire_protocol().builtin.initialPeersList.push_back(initial_peer_locator); // Publisher's channel

        pqos.transport().use_builtin_transports = false;
        std::shared_ptr<TCPv6TransportDescriptor> descriptor = std::make_shared<TCPv6TransportDescriptor>();
        descriptor->sendBufferSize = 8912896; // 8.5Mb
        descriptor->receiveBufferSize = 8912896; // 8.5Mb
        pqos.transport().user_transports.push_back(descriptor);
    }

    mp_participant = DomainParticipantFactory::get_instance()->create_participant(domain, pqos);

    if (mp_participant == nullptr)
    {
        return false;
    }

    //REGISTER THE TYPE
    std::string data_type;
    switch (m_iSize)
    {
        default:
        case 0:
            data_type = "messData";
            m_type.register_type(mp_participant);
            break;
        case 1:
            data_type = "smallData";
            m_typeSmall.register_type(mp_participant);
            break;
        case 2:
            data_type = "mediumData";
            m_typeMedium.register_type(mp_participant);
            break;
        case 3:
            data_type = "bigData";
            m_typeBig.register_type(mp_participant);
            break;
    }

    //CREATE THE SUBSCRIBER
    mp_subscriber = mp_participant->create_subscriber(SUBSCRIBER_QOS_DEFAULT);

    if (mp_subscriber == nullptr)
    {
        return false;
    }

    //CREATE THE TOPIC
    mp_topic_sub = mp_participant->create_topic(topicName, data_type, TOPIC_QOS_DEFAULT);

    if (mp_topic_sub == nullptr)
    {
        return false;
    }

    //CREATE THE DATAREADER
    DataReaderQos rqos;
    rqos.history().kind = KEEP_LAST_HISTORY_QOS;
    rqos.history().depth = 100;
    rqos.resource_limits().max_samples = 500;
    rqos.resource_limits().allocated_samples = 200;
    rqos.reliability().kind = reliabilityKind;
    rqos.durability().kind = VOLATILE_DURABILITY_QOS;
    rqos.data_sharing().automatic();

    mp_reader = mp_subscriber->create_datareader(mp_topic_sub, rqos, &m_subListener);

    if (mp_reader == nullptr)
    {
        return false;
    }

    return true;
}

zeroCopySubscriber::~zeroCopySubscriber()
{
    if (mp_reader != nullptr)
    {
        mp_subscriber->delete_datareader(mp_reader);
    }
    if (mp_subscriber != nullptr)
    {
        mp_participant->delete_subscriber(mp_subscriber);
    }
    if (mp_topic_sub != nullptr)
    {
        mp_participant->delete_topic(mp_topic_sub);
    }
    DomainParticipantFactory::get_instance()->delete_participant(mp_participant);
}


zeroCopySubscriber::SubListener::SubListener(
        zeroCopySubscriber* parent)
    : mParent(parent)
    , matched_(0)
    , samples_(0)
{
}

void zeroCopySubscriber::SubListener::on_subscription_matched(
        DataReader*,
        const SubscriptionMatchedStatus& info)
{
    if (info.current_count_change == 1)
    {
        matched_ = info.total_count;
        std::cout << "Subscriber matched." << std::endl;
    }
    else if (info.current_count_change == -1)
    {
        matched_ = info.total_count;
        std::cout << "Subscriber unmatched." << std::endl;
    }
    else
    {
        std::cout << info.current_count_change
                  << " is not a valid value for SubscriptionMatchedStatus current count change" << std::endl;
    }
}
const unsigned long Converter = 1000 * 1000; // 1s == 1000 * 1000 us
void zeroCopySubscriber::SubListener::on_data_available(
        DataReader* reader)
{
    struct  timeval  val;
    SampleInfo m_info;
    int g_ilimit = 0;
    bool g_bFinish = false;
    switch (mParent->m_iSize)
    {
        default:
        case 0:
        {
            if (mParent->m_iLoan > 0) {

                FASTDDS_SEQUENCE(DataSeq, messData);

                DataSeq data;
                SampleInfoSeq infos;
                while (ReturnCode_t::RETCODE_OK == reader->take(data, infos))
                {
                    for (LoanableCollection::size_type i = 0; i < infos.length(); ++i)
                    {
                        if (infos[i].valid_data)
                        {
                            gettimeofday(&val,NULL);
                            
                            // Print your structure data here.
                            const messData& sample = data[i];
    #ifdef VEC_DEBUG
                            mParent->m_vSimplesTime0.push_back(val.tv_sec * Converter + val.tv_usec);
                            mParent->m_vSimplesTime1.push_back(sample.timeSec() * Converter + sample.timeuSec());
    #else
                            mParent->m_iSimplesTime[0][sample.index()] = (val.tv_sec * Converter + val.tv_usec);
                            mParent->m_iSimplesTime[1][sample.index()] = (sample.timeSec() * Converter + sample.timeuSec());
    #endif
                            ++samples_;
                            g_ilimit = sample.maxLimit();
                            qlog_i("Sample received (index=%d samples=%#x) at address ",sample.index(), &sample);
                            if (sample.header() == 0xa5) {
                                std::cout << "messData test Successfully !"<< std::endl;
                                g_bFinish = true;
                            }
                        }
                    }
                    reader->return_loan(data, infos);
                }
            } else {
                // Take data
                // Keep taking data until there is nothing to take
                while (reader->take_next_sample(&m_Hello, &m_info) == ReturnCode_t::RETCODE_OK)
                // if (reader->take_next_sample(&m_Hello, &m_info) == ReturnCode_t::RETCODE_OK)
                {
                    // if (infos.instance_state == ALIVE_INSTANCE_STATE)
                    if (m_info.valid_data)
                    {
                        gettimeofday(&val,NULL);
#ifdef VEC_DEBUG
                            mParent->m_vSimplesTime0.push_back(val.tv_sec * Converter + val.tv_usec);
                            mParent->m_vSimplesTime1.push_back(m_Hello.timeSec() * Converter + m_Hello.timeuSec());
#else
                            mParent->m_iSimplesTime[0][st.index()] = (val.tv_sec * Converter + val.tv_usec);
                            mParent->m_iSimplesTime[1][st.index()] = (m_Hello.timeSec() * Converter + m_Hello.timeuSec());
#endif
                        // Print your structure data here.
                        ++samples_;
                        g_ilimit = m_Hello.maxLimit();
                        qlog_i("Sample received, count= %d ,data= %d",m_Hello.index(),m_Hello.metadata().front());
                        if (m_Hello.header() == 0xa5) {
                            qlog_i("messData test Successfully !");
                            g_bFinish = true;
                        }
                        
                    }
                }
            }
        }
        break;
        case 1:
        {
            if(mParent->m_iLoan > 0) {
            
                FASTDDS_SEQUENCE(DataSeq, smallData);

                DataSeq data;
                SampleInfoSeq infos;
                while (ReturnCode_t::RETCODE_OK == reader->take(data, infos))
                {
                    for (LoanableCollection::size_type i = 0; i < infos.length(); ++i)
                    {
                        if (infos[i].valid_data)
                        {
                            gettimeofday(&val,NULL);
                            // Print your structure data here.
                            const smallData& sample = data[i];
#ifdef VEC_DEBUG
                            mParent->m_vSimplesTime0.push_back(val.tv_sec * Converter + val.tv_usec);
                            mParent->m_vSimplesTime1.push_back(sample.timeSec() * Converter + sample.timeuSec());
#else
                            mParent->m_iSimplesTime[0][sample.index()] = (val.tv_sec * Converter + val.tv_usec);
                            mParent->m_iSimplesTime[1][sample.index()] = (sample.timeSec() * Converter + sample.timeuSec());
#endif
                            ++samples_;
                            g_ilimit = sample.maxLimit();
                            qlog_i("Sample received (data=%d index=%d samples=%#x) at address ",sample.data()[0],sample.index(), &sample);
                            if (sample.header() == 0xa5) {
                                std::cout << "smallData test Successfully !"<< std::endl;
                                g_bFinish = true;
                            }
                        }
                    }
                    reader->return_loan(data, infos);
                }
            } else {
                // Take data
                while (reader->take_next_sample(&m_HelloSmall, &m_info) == ReturnCode_t::RETCODE_OK)
                // if (reader->take_next_sample(&m_HelloSmall, &m_info) == ReturnCode_t::RETCODE_OK)
                {
                    if (m_info.valid_data)
                    // if (info.instance_state == ALIVE_INSTANCE_STATE)
                    {
                        gettimeofday(&val,NULL);
#ifdef VEC_DEBUG
                            mParent->m_vSimplesTime0.push_back(val.tv_sec * Converter + val.tv_usec);
                            mParent->m_vSimplesTime1.push_back(m_HelloSmall.timeSec() * Converter + m_HelloSmall.timeuSec());
#else
                            mParent->m_iSimplesTime[0][st.index()] = (val.tv_sec * Converter + val.tv_usec);
                            mParent->m_iSimplesTime[1][st.index()] = (m_HelloSmall.timeSec() * Converter + m_HelloSmall.timeuSec());
#endif
                        // Print your structure data here.
                        ++samples_;
                        g_ilimit = m_HelloSmall.maxLimit();
                        qlog_i("Sample received, count= %d ,data= %d",m_HelloSmall.index(),m_HelloSmall.data().front());
                        if (m_HelloSmall.header() == 0xa5) {
                            qlog_i("smallData test Successfully !");
                            g_bFinish = true;
                        }
                        
                    }
                }
            }
        }
        break;
        case 2:
        {
            if (mParent->m_iLoan > 0) {

                FASTDDS_SEQUENCE(DataSeq, mediumData);

                DataSeq data;
                SampleInfoSeq infos;
                while (ReturnCode_t::RETCODE_OK == reader->take(data, infos))
                {
                    for (LoanableCollection::size_type i = 0; i < infos.length(); ++i)
                    {
                        if (infos[i].valid_data)
                        {
                            gettimeofday(&val,NULL);
                            // Print your structure data here.
                            const mediumData& sample = data[i];
#ifdef VEC_DEBUG
                            mParent->m_vSimplesTime0.push_back(val.tv_sec * Converter + val.tv_usec);
                            mParent->m_vSimplesTime1.push_back(sample.timeSec() * Converter + sample.timeuSec());
#else
                            mParent->m_iSimplesTime[0][sample.index()] = (val.tv_sec * Converter + val.tv_usec);
                            mParent->m_iSimplesTime[1][sample.index()] = (sample.timeSec() * Converter + sample.timeuSec());
#endif
                            ++samples_;
                            g_ilimit = sample.maxLimit();
                            qlog_i("Sample received (data=%d index=%d samples=%#x) at address ",sample.data()[0],sample.index(), &sample);
                            if (sample.header() == 0xa5) {
                                qlog_i("mediumData test Successfully !");
                                g_bFinish = true;
                            }
                        }
                    }
                    reader->return_loan(data, infos);
                }
            } else {
                // Take data
                while (reader->take_next_sample(&m_HelloMedium, &m_info) == ReturnCode_t::RETCODE_OK)
                // if (reader->take_next_sample(&m_HelloMedium, &m_info) == ReturnCode_t::RETCODE_OK)
                {
                    if (m_info.valid_data)
                    // if (m_info.instance_state == ALIVE_INSTANCE_STATE)
                    {
                        gettimeofday(&val,NULL);
#ifdef VEC_DEBUG
                            mParent->m_vSimplesTime0.push_back(val.tv_sec * Converter + val.tv_usec);
                            mParent->m_vSimplesTime1.push_back(m_HelloMedium.timeSec() * Converter + m_HelloMedium.timeuSec());
#else
                            mParent->m_iSimplesTime[0][st.index()] = (val.tv_sec * Converter + val.tv_usec);
                            mParent->m_iSimplesTime[1][st.index()] = (m_HelloMedium.timeSec() * Converter + m_HelloMedium.timeuSec());
#endif
                        // Print your structure data here.
                        ++samples_;
                        g_ilimit = m_HelloMedium.maxLimit();
                        qlog_i("Sample received, count= %d ,data= %d",m_HelloMedium.index(),m_HelloMedium.data().front());
                        if (m_HelloMedium.header() == 0xa5) {
                            qlog_i("mediumData test Successfully !");
                            g_bFinish = true;
                        }
                        
                    }
                }
            }
        }
        break;
        case 3:
        {
            if (mParent->m_iLoan > 0) {

                FASTDDS_SEQUENCE(DataSeq, bigData);

                DataSeq data;
                SampleInfoSeq infos;
                while (ReturnCode_t::RETCODE_OK == reader->take(data, infos))
                {
                    for (LoanableCollection::size_type i = 0; i < infos.length(); ++i)
                    {
                        if (infos[i].valid_data)
                        {
                            gettimeofday(&val,NULL);
                            // Print your structure data here.
                            const bigData& sample = data[i];
                            
                            ++samples_;
#ifdef VEC_DEBUG
                            mParent->m_vSimplesTime0.push_back(val.tv_sec * Converter + val.tv_usec);
                            mParent->m_vSimplesTime1.push_back(sample.timeSec() * Converter + sample.timeuSec());
#else
                            mParent->m_iSimplesTime[0][sample.index()] = (val.tv_sec * Converter + val.tv_usec);
                            mParent->m_iSimplesTime[1][sample.index()] = (sample.timeSec() * Converter + sample.timeuSec());
#endif
                            g_ilimit = sample.maxLimit();
                            qlog_i("Sample received (data=%d index=%d samples=%#x) at address ",sample.data()[0],sample.index(), &sample);
                            if (sample.header() == 0xa5) {
                                qlog_i("bigData test Successfully !");
                                g_bFinish = true;
                            }
                        }
                    }
                    reader->return_loan(data, infos);
                }
            } else {
                // Take data
                while (reader->take_next_sample(&m_HelloBig, &m_info) == ReturnCode_t::RETCODE_OK)
                // if (reader->take_next_sample(&m_HelloBig, &m_info) == ReturnCode_t::RETCODE_OK)
                {
                    if (m_info.valid_data)
                    // if (info.instance_state == ALIVE_INSTANCE_STATE)
                    {
                        gettimeofday(&val,NULL);
#ifdef VEC_DEBUG
                            mParent->m_vSimplesTime0.push_back(val.tv_sec * Converter + val.tv_usec);
                            mParent->m_vSimplesTime1.push_back(m_HelloBig.timeSec() * Converter + m_HelloBig.timeuSec());
#else
                            mParent->m_iSimplesTime[0][st.index()] = (val.tv_sec * Converter + val.tv_usec);
                            mParent->m_iSimplesTime[1][st.index()] = (m_HelloBig.timeSec() * Converter + m_HelloBig.timeuSec());
#endif
                        // Print your structure data here.
                        ++samples_;
                        g_ilimit = m_HelloBig.maxLimit();
                        qlog_i("Sample received, count= %d ,data= %d",m_HelloBig.index(),m_HelloBig.data().front());
                        if (m_HelloBig.header() == 0xa5) {
                            qlog_i("bigData test Successfully !");
                            g_bFinish = true;
                        }
                        
                    }
                }
            }
        }
        break;
    }
#ifdef VEC_DEBUG
    if(g_bFinish){
        unsigned long diff = 0,diff1 = 0;
        double g_dDiff = 0,g_dSSpeed = 0,g_dRSpeed = 0;
        int i=0;
        if(mParent->m_vSimplesTime0.empty()){
            mParent->m_vSimplesTime0.clear();
            mParent->m_vSimplesTime1.clear();
            samples_ = 0;
            qlog_e("m_vSimplesTime0 is empty.");
            return;
        }
        diff = mParent->m_vSimplesTime0.back() - mParent->m_vSimplesTime0.front();
        diff1 = mParent->m_vSimplesTime1.back() - mParent->m_vSimplesTime1.front();
        if (diff == 0 || diff1 == 0) {
            qlog_i("time count:%d",mParent->m_vSimplesTime0.size());
        } else { 
            switch(mParent->m_iSize)
            {
                case 0:
                    break;
                case 1:
                    g_dSSpeed = (double)(10*Converter*g_ilimit/diff);//k/s
                    g_dSSpeed = g_dSSpeed/1024;
                    g_dRSpeed = (double)(10*Converter*g_ilimit/diff1);//k/s
                    g_dRSpeed = g_dRSpeed/1024;
                break;
                case 2:
                    g_dSSpeed = (double)(1*Converter*g_ilimit/diff);//M/s
                    g_dRSpeed = (double)(1*Converter*g_ilimit/diff1);//M/s
                break;
                case 3:
                    g_dSSpeed = (double)(10*Converter*g_ilimit/diff);//M/s
                    g_dRSpeed = (double)(10*Converter*g_ilimit/diff1);//M/s
                break;
            }
        }
        

        std::cout << "TOTAL: " << g_ilimit << std::endl;
        std::cout << "ACTUAL: " << samples_ << std::endl;
        std::cout << "LOSS RATE: " << ((g_ilimit - samples_)*100/g_ilimit) << "%" << std::endl;
        std::cout << "SEND SPEED: " << g_dSSpeed << "M/s" << std::endl;
        std::cout << "REVCIVER SPEED: " << g_dRSpeed << "M/s" << std::endl;
        i=0;
        for(auto it = mParent->m_vSimplesTime0.begin(); it != mParent->m_vSimplesTime0.end(); it++)
        {
            if (i > 100) {
                break;
            }
            diff = mParent->m_vSimplesTime0[i] - mParent->m_vSimplesTime1[i];
            g_dDiff =(double)(diff/1000);
            std::cout << "usec: " << diff << ",ms: " << g_dDiff << " | ";
            i++;
        }
        std::cout << std::endl;
        mParent->m_vSimplesTime0.clear();
        mParent->m_vSimplesTime1.clear();
        // mParent->m_vSimplesTime0.resize(2000);
        // mParent->m_vSimplesTime1.resize(2000);
        samples_ = 0;
    }
#else
    if(g_bFinish){
        unsigned long diff = 0,diff1 = 0;
        double g_dDiff = 0,g_dSSpeed = 0,g_dRSpeed = 0;
        int i=0;
        diff = mParent->m_iSimplesTime[0][samples_-1] - mParent->m_iSimplesTime[0][0];
        diff1 = mParent->m_iSimplesTime[1][samples_-1] - mParent->m_iSimplesTime[1][0];
        switch(mParent->m_iSize)
        {
            case 0:
                break;
            case 1:
                g_dSSpeed = (double)(10*Converter*g_ilimit/diff);//k/s
                g_dSSpeed = g_dSSpeed/1024;
                g_dRSpeed = (double)(10*Converter*g_ilimit/diff1);//k/s
                g_dRSpeed = g_dRSpeed/1024;
            break;
            case 2:
                g_dSSpeed = (double)(1*Converter*g_ilimit/diff);//M/s
                g_dRSpeed = (double)(1*Converter*g_ilimit/diff1);//M/s
            break;
            case 3:
                g_dSSpeed = (double)(10*Converter*g_ilimit/diff);//M/s
                g_dRSpeed = (double)(10*Converter*g_ilimit/diff1);//M/s
            break;
        }
        std::cout << "TOTAL: " << g_ilimit << std::endl;
        std::cout << "ACTUAL: " << samples_ << std::endl;
        std::cout << "LOSS RATE: " << ((g_ilimit - samples_)/g_ilimit)*100 << "%" << std::endl;
        std::cout << "SEND SPEED: " << g_dSSpeed << "M/s" << std::endl;
        std::cout << "REVCIVER SPEED: " << g_dRSpeed << "M/s" << std::endl;
        for(i=0;i<g_ilimit;i++)
        {
            diff = mParent->m_iSimplesTime[0][i] - mParent->m_iSimplesTime[1][i];
            g_dDiff =(double)(diff/1000);
            std::cout << "usec: " << diff << ",ms: " << g_dDiff << " | ";
        }
        std::cout << std::endl;
        samples_ = 0;
    }
#endif // DEBUG VEC
    
}

void zeroCopySubscriber::runThread()
{
    int iPrevCount = 0;
    qlog_i("ReviceListener running...");
    // Prepare a wait-set to wait for data on the DataReader
    // WaitSet wait_set;
    // StatusCondition& condition = data_reader->get_statuscondition();
    // condition.set_enabled_statuses(StatusMask::data_available());
    // wait_set.attach_condition(condition);
    // // Create a data and SampleInfo instance
    // Foo data;
    // SampleInfo info;
    // //Define a timeout of 5 seconds
    // eprosima::fastrtps::Duration_t timeout (5, 0);
}

void zeroCopySubscriber::run()
{
    qlog_i("Subscriber running..." );
    std::cin.ignore();
    std::thread thread(&zeroCopySubscriber::runThread, this);

    thread.join();
}
